<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic\withdraw;

use \think\Db;

class WithdrawLogic
{
    protected $function_alias_list = [ //方法别名
        1 => 'handleWithdrawState_1', //1、已审核
        2 => 'handleWithdrawState_2', //2、提现（放款中）
        3 => 'handleWithdrawState_3', //3、提现（提现完成）
        4 => 'handleWithdrawState_4', //4、被拒绝（失败）  //
    ];

    /**
     * User:Simony
     * Function: 处理提现操作
     * @param $id
     * @param $state
     * @return mixed
     */
    public function handleWithdrawOp($id, $state, $reason = '')
    {
        $fucntionName = $this->function_alias_list[$state];
        if (!method_exists($this, $fucntionName)) {
            ds_arr('err', '参数有误');
        }
        return $this->$fucntionName($id, $reason);
    }

    /**
     * User:Simony
     * Function: 提现状态操作    1、已审核
     * @param $id
     * @param int $state 这个参数默认且以后都不设置
     * @return array
     */
    public function handleWithdrawState_1($id, $reason = '')
    {
        //model
        $withdrawModel = model('common/withdraw/Withdraw');
        $withdraw = $withdrawModel->getInfoByID($id);

        if (!$withdraw) return ds_arr('err', '数据不存在');
        if ($withdraw['state'] == 1) return ds_arr('err', '该数据已处理，请勿重复处理');

        $withdrawModel->setValById($id, 'state', 1);
        return ds_arr('ret', '操作成功');
    }

    /**
     * User:Simony
     * Function: 提现状态操作    2、提现（放款中）
     * @param $id
     * @param int $state 这个参数默认且以后都不设置
     * @return array
     */
    public function handleWithdrawState_2($id, $reason = '')
    {
        //model
        $withdrawModel = model('common/withdraw/Withdraw');
        $withdraw = $withdrawModel->getInfoByID($id);

        if (!$withdraw) return ds_arr('err', '数据不存在');
        if ($withdraw['state'] != 1) return ds_arr('err', '该数据已处理，请勿重复处理');

        $withdrawModel->setValById($id, 'state', 2);
        return ds_arr('ret', '操作成功');
    }

    /**
     * User:Simony
     * Function: 提现状态操作     3、提现（提现完成)
     * @param $id
     * @param int $state 这个参数默认且以后都不设置
     * @return array
     */
    public function handleWithdrawState_3($id, $reason = '')
    {

        //model
        $withdrawModel = model('common/withdraw/Withdraw');
        $withdraw = $withdrawModel->getInfoByID($id);

        if (!$withdraw) return ds_arr('err', '数据不存在');
        if ($withdraw['state'] != 2) return ds_arr('err', '放款中才可以支付');


        try {

            //余额变更+log 在提现操作的时候就已经完成了
            $withdraw_res = $withdrawModel->editByID($id,['state'=>3,'complate_time'=>time()]);

            if (!$withdraw_res) {
                Db::rollback();
                return ds_arr('err', '设置提现状态失败');
            }

            $appAliPayLogic = model('common/AppAliPayLogic', 'logic');
            $res = $appAliPayLogic->singleTransfer($withdraw['order_sn'], $withdraw['account'], $withdraw['account_name'], $withdraw['price']);

            if ($res['code'] !== 200) return ds_arr('err', $res['msg'],$res['result']);


            return ds_arr('ret', '操作成功');
        } catch (\Exception $e) {
            // 回滚事务
            return ds_arr('err', '操作失败');
        }

    }

    /**
     * User:Simony
     * Function: 提现状态操作 4、被拒绝（失败）
     * @param $id
     * @param int $state 这个参数默认且以后都不设置
     * @return array
     */
    public function handleWithdrawState_4($id, $reason = '')
    {

        //model
        $withdrawModel = model('common/withdraw/Withdraw');


        $withdraw = $withdrawModel->getInfoByID($id);

        if (!$withdraw) return ds_arr('err', '数据不存在');

        try {

            //余额变更+log 在提现操作的时候就已经完成了

            //添加退还日志+变更回来金额
            $res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($withdraw['member_id'], $withdraw['money'], 0, 2, '提现失败退还金额', $withdraw['id']);
            if ($res['code'] != SUCCESS) return ds_arr('err', $res['msg']);


            $update_data = [
                'state' => 4,
                'reason' => $reason
            ];

            $withdraw_res = $withdrawModel->editByID($id, $update_data);
            if (!$withdraw_res) return ds_arr('err', '设置提现状态失败');

            return ds_arr('ret', '操作成功');
        } catch (\Exception $e) {
            return ds_arr('err', '操作失败');
        }

    }

    /**
     * User: Simony
     * Function:提现
     * @param $member_id
     * @param $money
     * @param $paymethod 1 微信 2 支付宝 3银行卡
     * @return array
     */
    public function withdrawal($member_id, $money, $paymethod)
    {
        if (!in_array($paymethod, [2])) return ds_arr(ERROR, '目前只支持支付宝');

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);

        if (empty($member)) return ds_arr(ERROR, '会员不存在');
        if (floatval($member['available_balance']) < floatval($money)) return ds_arr(ERROR, '金额不足');

        if (empty($member['alipay']) || empty($member['alipay_name'])) return ds_arr(ERROR, '提现支付宝，跟支付宝名称不能为空');

        $withdrawModel = model('common/withdraw/Withdraw');

        $where = [
            'member_id' => $member_id,
            'state' => 0,
        ];
        $isExist = $withdrawModel->isExist($where);
        if ($isExist) return ds_arr(ERROR, '存在未完成的提现');

        $platform = sysConfig('platform');
        $fee_rate = isset($platform['withdrawal_fee_rate']) ? $platform['withdrawal_fee_rate'] : 0;
        $rate = isset($platform['withdrawal_rate']) ? $platform['withdrawal_rate'] : 0;
        $tax_money = $money * round($fee_rate / 100, 4);
        $real_money = $money - $tax_money;

        $price = $rate > 0 ? round($real_money / $rate, 2) : round($real_money, 2);

        $order_sn = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $add_withdraw_data = [
            'order_sn' => $order_sn,
            'member_id' => $member_id,
            'state' => 0,
            'money' => $money,
            'tax_money' => $tax_money,
            'real_money' => $real_money,
            'create_time' => time(),
            'price' => $price,
            'paymethod' => $paymethod
        ];

        if ($paymethod == 2) {
            $add_withdraw_data['account'] = $member['alipay'];
            $add_withdraw_data['account_name'] = $member['alipay_name'];
        }

        $add_withdraw_res = $withdrawModel->add($add_withdraw_data);
        if (!$add_withdraw_res) ds_arr(ERROR, '添加提现记录失败');

        //先扣款
        $res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($member_id, -$money, 0, 2, '提现扣款', $add_withdraw_res);

        return ds_arr($res['code'], $res['msg'], $res['result']);
    }

}
